#include <signal.h>
#include "../Common/httplib.h"
using namespace httplib;
#include "oj_control.hpp"


#define WWWROOT "./wwwroot"

void Usage(const std::string& cmd){
    std::cout << "Please use the command of : " << cmd << " sevrer_port" << std::endl; 
    exit(-1);
}

static Control* ctrl_ptr = nullptr;

void RecoverMachine(int signo){ctrl_ptr->RecoverAllMachine();}

int main(int argc, char* argv[]){
    if(argc != 2) Usage(argv[0]);

    Server svr;
    svr.set_base_dir(WWWROOT);
    Control ctrl;
    ctrl_ptr = &ctrl;

    signal(SIGQUIT, RecoverMachine);

    //1.能够获取到所有的题目列表
    svr.Get("/all_questions", [&ctrl](const Request& req, Response& resp){
        std::string all_ques_html;
        ctrl.AllQuestion(&all_ques_html);
        resp.set_content(all_ques_html.c_str(), "text/html; charset=utf-8");
    });

    //2.根据题目编号进入题目解答页面 （用正则表达式进行匹配！）
    //因为到时候HTTP协议内，提取url的时候，是通关正则表达式进行匹配和提取的！(这个我们自己也写过)
    //然后这里只进行题号提取，所以再matches内，坐标0是整个url，坐标1就是要请求的资源
    svr.Get(R"(/question/(\d+))", [&ctrl](const Request& req, Response& resp){
        std::string number = req.matches[1], ques_html;
        ctrl.Question(number, &ques_html);
        resp.set_content(ques_html.c_str(), "text/html; charset=utf-8");
    });

    /*还未和control进行联动*/
    //3.能写题目，并且(提交判题)
    svr.Post(R"(/judge/(\d+))", [&ctrl](const Request& req, Response& resp){
        std::string num = req.matches[1];
        std::string out_json;
        ctrl.Judge(num, req.body, &out_json);
        resp.set_content(out_json.c_str(), "application/json; charset=utf-8");
    });


    svr.listen("0.0.0.0", std::stoi(argv[1]));
    return 0;
}